package data;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class InputFileReader implements Runnable {
	private FileReader reader;
	private File file;
	private char valSepChar = ' ';
	private char recSepChar = '\n';
	private boolean end = false;
	private InputFileRelay relay;
	private int length = 20;
	private char[] buff;
	private int restEnd = 0; 
	
	public InputFileReader(File file, InputFileRelay relay) {
		this.file = file;
		this.relay = relay;
		buff = new char[length];
	}

	@Override
	public void run() {
		try {
			reader = new FileReader(file);
			while (!end) {
				readRecord();
			}
		} 
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}		
	}
	
	private void readRecord() {
		try {
			if (reader.ready()) {
				reader.read(buff, restEnd, length - restEnd);
				
				String sbuff = new String(buff);
				int valEnd = sbuff.indexOf(valSepChar);
				int interval = Integer.parseInt(sbuff.substring(0, valEnd));
				int recEnd = sbuff.indexOf(recSepChar);
				int lane = Integer.parseInt(sbuff.substring(valEnd + 1, recEnd));
				
				System.out.println(lane + " " + interval);
				relay.addRecord(new InputFileRecord(lane, interval));
				
				String rest = sbuff.substring(recEnd + 1);
				restEnd = rest.length();
				System.arraycopy(rest.toCharArray(), 0, buff, 0, restEnd);
			}
		}  
		catch (IOException e) {
			e.printStackTrace();
		}		
	}
}